package com.jiepos.mpos.biz.user.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jiepos.mpos.common.constant.SystemConstant;
import com.jiepos.mpos.common.dao.UserRoleDao;
import com.jiepos.mpos.common.entity.App_UserRole_InfEntity;
import com.jiepos.mpos.core.service.BaseService;
import com.jiepos.mpos.core.util.IDFactoryUtil;

/**
 * @ClassName: UserRoleService
 * @Description: 用户角色服务层
 * @author 孙永
 * @date 2017年9月26日 上午11:17:46
 */
@Service
public class UserRoleService extends BaseService {

	@Autowired
	private UserRoleDao userRoleDao;
	
	/**
	 * 根据用户代码查询可使用的角色
	 * @param user_uuid 用户代码
	 * @return
	 */
	public App_UserRole_InfEntity getUserRoleByUserUuid(String user_uuid){
		App_UserRole_InfEntity entity = userRoleDao.findByParam("user_uuid", user_uuid);
		return entity == null ? new App_UserRole_InfEntity() : entity;
	}
	
	/**
	 * 保存用户 角色
	 * @param entity
	 * @param map
	 * @return
	 */
	public boolean saveUserRole(App_UserRole_InfEntity entity, Map map){
		if(entity == null){
			return false;
		}
		entity.setRec_upd_usr_id(String.valueOf(map.get(SystemConstant.SESSION_LOGIN_USER)));
		App_UserRole_InfEntity oldEntity = userRoleDao.findByParam("user_uuid", entity.getUser_uuid());
		if (oldEntity != null) {// 修改
			oldEntity.setRole_uuid(entity.getRole_uuid());
			oldEntity.setRec_upd_ts(new Timestamp(System.currentTimeMillis()));
			oldEntity.setRec_id(oldEntity.getRec_id());
			oldEntity.setRec_crt_ts(oldEntity.getRec_crt_ts());
			oldEntity.setLast_oper_in(SystemConstant.OPER_UPDATE);
			List noChangeList = new ArrayList();
			noChangeList.add("userrole_uuid");
			noChangeList.add("user_uuid");
			userRoleDao.update(oldEntity, noChangeList);
		} else {// 新增
			entity.setRec_crt_ts(new Timestamp(System.currentTimeMillis()));
			entity.setRec_upd_ts(new Timestamp(System.currentTimeMillis()));
			entity.setUserrole_uuid(IDFactoryUtil.getUUID());
			entity.setLast_oper_in(SystemConstant.OPER_ADD);
			userRoleDao.save(entity);
		}
		return true;
	}
}
